<?php

namespace app\common;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;
use think\Exception;

abstract class BaseModel extends Model
{
    const DISABLED_STATUS = 0;//后台账号禁用状态
    const ENABLED_STATUS = 1;//后台账号启用状态
    const NO_DELETED = 0;//未删除
    const YES_DELETED = 1;//已删除

    /**
     * 根据ID查询数据
     * @param $id
     * @return BaseModel|array|mixed|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function findById($id)
    {
        return static::findNoDeleted(['id' => $id]);
    }

    /**
     * 未删除的数据
     * @param array $where
     * @return BaseModel|array|mixed|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function findNoDeleted(array $where = [])
    {
        $where = array_merge($where, ['is_deleted' => self::NO_DELETED]);
        return static::where($where)->find();
    }

    /**
     * 保存数据
     * @param $data
     * @return void
     */
    public static function saveData($data)
    {

    }

    /**
     * 删除数据
     * @param $data
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public static function delData($data)
    {
        $id = !empty($data['id']) ? $data['id'] : 0;

        $modelRecord = static::findNoDeleted(['id' => $id]);
        if (empty($modelRecord)) {
            throw new Exception('未知数据');
        }

        $modelRecord->is_deleted = self::YES_DELETED;
        $modelRecord->deleted_at = date('Y-m-d H:i:s');
        $modelRecord->save();
    }
}